package com.linkoog.devtools.http.request.http_response.response.response_header;

import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.ui.JBUI;
import com.linkoog.devtools.intellij.ui.table.ListTableView;
import com.linkoog.devtools.intellij.ui.table.row_data.KeyValTableRowData;
import com.linkoog.devtools.utils.StringUtils;
import lombok.Getter;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ResponseHeaderPanel extends JBScrollPane{

    @Getter
    private final ListTableView<KeyValTableRowData> headersTable;

    public ResponseHeaderPanel() {
        headersTable = KeyValTableRowData.createListTableView();
        headersTable.setBackground(JBColor.WHITE);
        headersTable.setCellSelectionEnabled(true);

        this.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        this.setBorder(JBUI.Borders.customLineTop(new JBColor(Gray._214, new Color(30, 31, 34))));
        this.setViewportView(headersTable);
    }

    public void reset(Map<String, List<String>> headers){
        if (headers != null && !headers.isEmpty()) {
            List<KeyValTableRowData> headersList = new ArrayList<>();
            for (String headerName : headers.keySet()) {
                if (StringUtils.isBlank(headerName)) continue;

                List<String> headerValues = headers.get(headerName);
                if (headerValues == null || headerValues.isEmpty()) {
                    headersList.add(new KeyValTableRowData(headerName, ""));
                } else {
                    for (String headerValue : headerValues) {
                        if (StringUtils.isBlank(headerValue)) headerValue = "";
                        headersList.add(new KeyValTableRowData(headerName, headerValue));
                    }
                }
            }
            headersTable.reloadData(headersList);
        }
    }

}
